package org.jaaksi.kottlindemo

import kotlinx.coroutines.*
import org.junit.experimental.theories.suppliers.TestedOn
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine

fun main() = test4()

fun test4() = runBlocking {
    val job = launch {
        try {
            repeat(1000) { i ->
                println("job: I'm sleeping $i ...")
                delay(500L)
            }
        } finally {
            println("job: I'm running finally")
        }
    }
    delay(1300L) // 延迟一段时间
    println("main: I'm tired of waiting!")
    job.cancelAndJoin() // 取消该作业并且等待它结束
    println("main: Now I can quit.")
}

fun test3() = runBlocking {
    val startTime = System.currentTimeMillis()
    val job = launch(Dispatchers.Default) {
        var nextPrintTime = startTime
        var i = 0
        while (i < 5 && isActive) { // 一个执行计算的循环，只是为了占用 CPU
            // 每秒打印消息两次
            if (System.currentTimeMillis() >= nextPrintTime) {
                println("job: I'm sleeping ${i++} ...")
                nextPrintTime += 500L
            }
        }
    }
    delay(1300L) // 等待一段时间
    println("main: I'm tired of waiting!")
    job.cancelAndJoin() // 取消一个作业并且等待它结束
    println("main: Now I can quit.")
}


suspend fun sus() = suspendCoroutine<String> {
    it.resume("1")
}

fun test1(){
    // runBlocking
    //delay start
    //delay end
    //2222
    println("runBlocking")
    runBlocking {
        println("delay start")
        delay(1000)
        println("delay end")
    }
    println("2222")

}


fun test2(){
    // GlobalScope launch
    //2222
    //delay start
    //delay end
    println("GlobalScope launch")
    GlobalScope.launch(Dispatchers.Main) {
        println("delay start")
        delay(1000)
        println("delay end")
    }
    println("2222")
    Thread.sleep(2000L) // 阻塞主线程 2 秒钟来保证 JVM 存活
}